package com.kung.qvs.ui.main.fragment.manage;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableField;
import androidx.databinding.ObservableList;

import com.kung.qvs.BR;
import com.kung.qvs.R;
import com.kung.qvs.data.JtRepository;
import com.kung.qvs.entity.BaseResultBean;
import com.kung.qvs.entity.ProductBean;
import com.kung.qvs.entity.ProductTypeBean;
import com.kung.qvs.entity.SpinnerItemData;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.observers.DisposableObserver;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.http.ResponseThrowable;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;
import me.tatarka.bindingcollectionadapter2.ItemBinding;

public class FragProductsModel extends BaseViewModel<JtRepository> {
    public FragProductsModel(@NonNull Application application, JtRepository model) {
        super(application, model);
    }

    //封装一个界面发生改变的观察者
    public UIChangeObservable uc = new UIChangeObservable();

    public class UIChangeObservable {
        //下拉刷新完成
        public SingleLiveEvent eventToLastPage = new SingleLiveEvent<>();
        public SingleLiveEvent<ProductBean> eventEditProduct = new SingleLiveEvent<>();
        public SingleLiveEvent<ProductBean> eventDeleteProduct = new SingleLiveEvent<>();
        public SingleLiveEvent eventAddProduct = new SingleLiveEvent();
    }

    public List<ProductTypeBean> productTypeBeans = new ArrayList<>();

    public ObservableField<String> mCount = new ObservableField<>("0");    //收集数量

    //给RecyclerView添加ObservableList
    public ObservableList<FragProductsItem> observableList = new ObservableArrayList<>();
    //给RecyclerView添加ItemBinding
    public ItemBinding<FragProductsItem> itemBinding = ItemBinding.of(BR.viewModel, R.layout.item_product_record);

    public BindingCommand onPageBack = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            uc.eventToLastPage.call();
        }
    });

    public BindingCommand onAddData = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            uc.eventAddProduct.call();
        }
    });

    public void funLoadProducts() {
        observableList.clear();
        mCount.set("0");
        model.reqSynchronizeProducts("", model.getEquipmentNo()).compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        showDialog("正在请求数据...");
                    }
                })
                .subscribe(new DisposableObserver<BaseResultBean<List<ProductBean>>>() {
                    @Override
                    public void onNext(BaseResultBean<List<ProductBean>> response) {
                        //请求成功
                        if (response.isSuccess()) {
                            //数据插入本地，并根据id排序查询。已被无网络情况使用
                            int index = 1;
                            for(ProductBean bean : response.entity) {
                                bean.setIndex(index++ + "");
                                observableList.add(new FragProductsItem(FragProductsModel.this, bean));
                            }
                            mCount.set(response.entity.size() + "");
                        } else {
                            //code错误时也可以定义Observable回调到View层去处理
                            ToastUtils.showShort(response.desc);
                        }
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        //关闭对话框
//                        dismissDialog();
                        if (throwable instanceof ResponseThrowable) {
                            ToastUtils.showShort(((ResponseThrowable) throwable).message);
                            //token失效，重新登录
//                            finish();
                            //如果无网络，使用本地缓存垃圾分类
                        }
                    }

                    @Override
                    public void onComplete() {
                        //关闭对话框
                        dismissDialog();
                    }
                });
    }

    public void funDeleteProduct(ProductBean bean) {
        model.reqDeleteProductBean("", model.getEquipmentNo(), bean.getProductId()).compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        showDialog("正在删除数据...");
                    }
                })
                .subscribe(new DisposableObserver<BaseResultBean<Integer>>() {
                    @Override
                    public void onNext(BaseResultBean<Integer> response) {
                        //请求成功
                        if (response.isSuccess()) {
                            //数据插入本地，并根据id排序查询。已被无网络情况使用
                            funLoadProducts();
                        } else {
                            //code错误时也可以定义Observable回调到View层去处理
                            ToastUtils.showShort(response.desc);
                        }
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        //关闭对话框
//                        dismissDialog();
                        if (throwable instanceof ResponseThrowable) {
                            ToastUtils.showShort(((ResponseThrowable) throwable).message);
                            //token失效，重新登录
//                            finish();
                            //如果无网络，使用本地缓存垃圾分类
                        }
                    }

                    @Override
                    public void onComplete() {
                        //关闭对话框
                        dismissDialog();
                    }
                });
    }

    public void funLoadProductTypes() {
        //加载产品类型
        model.reqSynchronizeProductTypes("", model.getEquipmentNo()).compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        showDialog("正在请求数据...");
                    }
                })
                .subscribe(new DisposableObserver<BaseResultBean<List<ProductTypeBean>>>() {
                    @Override
                    public void onNext(BaseResultBean<List<ProductTypeBean>> response) {
                        //请求成功
                        if (response.isSuccess()) {
                            //数据插入本地，并根据id排序查询。已被无网络情况使用
                            productTypeBeans = response.entity;
                        } else {
                            //code错误时也可以定义Observable回调到View层去处理
                            ToastUtils.showShort(response.desc);
                        }
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        //关闭对话框
//                        dismissDialog();
                        if (throwable instanceof ResponseThrowable) {
                            ToastUtils.showShort(((ResponseThrowable) throwable).message);
                            //token失效，重新登录
//                            finish();
                            //如果无网络，使用本地缓存垃圾分类
                        }
                    }

                    @Override
                    public void onComplete() {
                        //关闭对话框
                        dismissDialog();
                    }
                });
    }
}
